/*** manager ***/
package main;

import comm.Login;
import java.util.ArrayList;
import java.util.List;

public class User {

  private static String login;
  private static String pass;
  private static List<Contact> contacts;

  public static String getLogin() {
    return login;
  }

  public static void setLogin(String login) {
    User.login = login;
  }

  public static String getPass() {
    return pass;
  }

  public static void setPass(String pass) {
    User.pass = pass;
  }

  public static boolean login() {
    return new Login(login, pass).isConnected();
  }

  public static boolean login(String login, String pass) {
    User.login = login;
    User.pass = pass;
    return new Login(login, pass).isConnected();
  }

  public static void addContact(Contact c) {
    if (contacts == null) {
      contacts = new ArrayList<Contact>();
    }
    if (indexOfContact(c) != -1) {
      return;
    }
    contacts.add(c);
  }

  public static void addContact(String name, String phone, String email) {
    addContact(new Contact(name, phone, email));
  }

  public static String[] getContactsHeaders() {
    return Contact.HEADERS;
  }

  public static String[][] getContactsData() {

    if (contacts == null) {
      return null;
    }
    String[][] res = new String[contacts.size()][Contact.HEADERS_NUMBER];
    for (int i = 0; i < contacts.size(); i++) {
      res[i] = contacts.get(i).toArray();
    }
    return res;

  }

  public static void editContact(Contact c, String name, String phone, String email) {
    int index = indexOfContact(c);
    if (index == -1) {
      return;
    }
    contacts.remove(index);
    if (name == null || name.equals("")) {
      name = c.getName();
    }
    if (phone == null || phone.equals("")) {
      phone = c.getPhone();
    }
    if (email == null || email.equals("")) {
      email = c.getEmail();
    }
    addContact(name, phone, email);
  }

  public static int indexOfContact(Contact c) {
    if (c == null) {
      return -1;
    }
    for (int i = 0; i < contacts.size(); i++) {
      if (contacts.get(i).equals(c)) {
        return i;
      }
    }
    return -1;
  }

  public static void saveContacts(String[][] data) {
    contacts.clear();
    for (String[] row : data) {
      if (row.length == Contact.HEADERS_NUMBER) {
        addContact(row[0], row[1], row[2]);
      }
    }
  }
}
